import React, { forwardRef, useImperativeHandle } from 'react';
import { connect } from 'dva';
import { Popconfirm, Modal, Button, Table, Input, message, Spin } from 'antd';
import styles from './index.less';
let repeatKeys = [];
let formList = [];
import { Form } from '@ant-design/compatible';

const EditableContext = React.createContext();
const EditableRow = forwardRef(({ form, index, ...props }, ref) => {
  useImperativeHandle(ref, () => ({
    form,
  }));
  return (
    <EditableContext.Provider value={form}>
      <tr {...props} />
    </EditableContext.Provider>
  );
});

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
    isAvailable: true,
  };

  // toggleEdit = (form) => {
  //   const editing = !this.state.editing;
  //   this.setState({ editing }, () => {
  //     if (editing) {
  //       this.input.focus();
  //     }
  //   });
  // };

  save = (e) => {
    const { record, handleSave } = this.props;
    this.form.validateFields({ force: true }, (error, values) => {
      if (error && error[e.currentTarget.id]) {
        console.log(error);
        // return;
      }
      // this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = (form) => {
    this.form = form;
    // console.log(form.validateFields());
    // console.log(repeatKeys);
    const { children, dataIndex, record, title, rules } = this.props;
    const { editing } = this.state;
    // let index = 0;
    // const repeat = formList.find((o, i) => {
    //   index = i;
    //   return o.key == record.key;
    // });
    // if (repeat) {
    //   formList[index].form = form;
    // } else {
    //   formList.push({
    //     key: record.key,
    //     form,
    //   });
    // }
    // console.log(formList);
    // return editing ? (
    return (
      <Form.Item
        style={{ margin: 0 }}
        // validateStatus={
        //   repeatKeys.includes(record.key) || !record.name ? "error" : "success"
        // }
      >
        {form.getFieldDecorator(dataIndex, {
          rules,
          initialValue: record[dataIndex],
        })(
          <Input
            ref={(node) => (this.input = node)}
            onPressEnter={this.save}
            onBlur={this.save}
            onPause={this.save}
            maxLength={32}
          />,
        )}
      </Form.Item>
      // ) : (
      //   <div
      //     className={styles["editable-cell-value-wrap"]}
      //     style={{ paddingRight: 24 }}
      //     onClick={this.toggleEdit}
      //   >
      //     {children}
      //   </div>
    );
  };

  render() {
    const { editable, dataIndex, title, record, index, handleSave, children, ...restProps } =
      this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

@connect(({ fieldSetting }) => ({
  fieldSetting,
}))
export default class GroupModal extends React.Component {
  constructor(props) {
    super(props);
    const { dispatch } = props;
    this.state = {
      // loading: false,
      dataSource: [],
      count: 0,
      delList: [],
    };
    dispatch({
      type: 'fieldSetting/groupList',
      payload: {
        url: '/mscreditbusiness/credit/field/group/list',
      },
      callback: (res) => {
        // console.log(res);
        const list = res.data?.map((item, index) => {
          return {
            key: index,
            ...item,
          };
        });
        this.setState({
          dataSource: list,
          count: list.length,
        });
      },
    });
  }

  handleAdd = () => {
    const { dataSource, count } = this.state;
    const newData = {
      key: count,
      name: '',
      type: 1,
      delStatus: 1,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  handleDelete = (key) => {
    const { dataSource, delList } = this.state;
    const delItem = dataSource.find((item) => item.key === key);
    if (delItem.uuid) this.setState({ delList: [...delList, delItem.uuid] });
    const newData = dataSource.filter((item) => item.key !== key);
    repeatKeys = repeatKeys.filter((i) => i !== key);
    this.setState({ dataSource: newData });
  };
  handleSave = (row) => {
    const { dataSource } = this.state;
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({
      dataSource: newData,
    });
  };

  handleSubmit = () => {
    const { changeVisible, dispatch } = this.props;
    const { dataSource, delList } = this.state;
    // this.setState({ loading: true });
    const saveList = dataSource.filter((item) => item.type === 1);
    if (saveList.find((item) => !item.name)) {
      message.error('分组名称不能为空，请检查');
      return;
    }
    if (saveList.find((item) => item.name?.length > 32)) {
      message.error('分组名称长度不超过32位，请检查');
      return;
    }
    const params = {
      saveList,
      delList,
    };
    // console.log(this.state.dataSource, params);

    // setTimeout(() => {
    dispatch({
      type: 'fieldSetting/groupSave',
      payload: {
        url: '/mscreditbusiness/credit/field/group/save',
        ...params,
      },
      callback: (res) => {
        if (res.statusCode == '0') {
          message.success('保存成功');
          // this.setState({ loading: false });
          changeVisible();
        } else {
          message.error(res.statusMessage);
        }
      },
    });
    // }, 3000);
  };

  checkUniq = (rule, value, callback, key) => {
    const { dataSource } = this.state;
    // console.log(rule, value, dataSource, key);

    if (!value) {
      callback();
      return;
    } //value为空跳过重复校验
    if (dataSource.find((item) => item.name === value && item.key !== key)) {
      !repeatKeys.find((i) => i === key) && repeatKeys.push(key);
      callback('字段名称不可重复');
      // return;
    } else {
      repeatKeys = repeatKeys.filter((i) => i !== key);
      callback();
    }
    // callback();
  };
  render() {
    const {
      visible,
      changeVisible,
      fieldSetting: { modalLoading },
    } = this.props;
    const { dataSource } = this.state;
    const components = {
      body: {
        // row: () => {
        //   const formRef = createRef();
        //   return <EditableFormRow wrappedComponentRef={formRef} />;
        // },
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = [
      {
        title: '字段分组',
        dataIndex: 'name',
        editable: true,
        onCell: (record) => ({
          record,
          editable: record.type == 1, //ii.	已经增加的分组信息，可以修改
          dataIndex: 'name',
          title: '字段分组',
          handleSave: this.handleSave,
          rules: [
            {
              required: true,
              message: `字段分组必填`,
            },
            {
              max: 32,
              type: 'string',
              message: `长度不超过32位`,
            },
            {
              validator: (rule, value, callback) =>
                this.checkUniq(rule, value, callback, record.key),
            },
          ],
        }),
      },
      {
        title: '操作',
        dataIndex: 'opt',
        render: (_, record) =>
          record.type == 1 &&
          record.delStatus == 1 && (
            <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.key)}>
              <a>删除</a>
            </Popconfirm>
          ),
      },
    ];

    const currentCount = dataSource.length - dataSource.filter((item) => item.type == 0)?.length; //  当前数量：list的数量 - 预设分组的数量
    return (
      <Modal
        title="字段分组"
        style={{ top: 20 }}
        width="40%"
        visible={visible}
        closable={false}
        onCancel={() => changeVisible()}
        maskClosable={false}
        footer={[
          <Button key="back" size="small" onClick={() => changeVisible()}>
            取消
          </Button>,

          <Button
            key="submit"
            size="small"
            type="primary"
            loading={modalLoading}
            onClick={this.handleSubmit}
          >
            保存
          </Button>,
        ]}
      >
        <Spin spinning={modalLoading}>
          <div>
            <div style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                size="small"
                onClick={this.handleAdd}
                disabled={currentCount === 10}
              >
                {`新增字段分组（${currentCount}/10）`}
              </Button>
            </div>
            <Table
              components={components}
              rowClassName={() => styles['editable-row']}
              bordered
              dataSource={dataSource}
              columns={columns}
              pagination={false}
            />
          </div>
        </Spin>
      </Modal>
    );
  }
}
